package com.weishao.dbmapper.engine.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import com.weishao.dbmapper.IResultRowHandler;
import com.weishao.dbmapper.engine.AbstractMapperService;
import com.weishao.dbmapper.engine.IMapperService;
import com.weishao.dbmapper.pojo.TaskParamEntity;

/**
 * 多对一映射转换类
 * 
 * @author tang
 *
 */
public class MultByOneMapperImpl extends AbstractMapperService implements IMapperService {

	public MultByOneMapperImpl(DataSource dataSource, int fetchSize, boolean quiet) {
		super(dataSource, fetchSize, quiet);
	}

	@Override
	public void mapper(TaskParamEntity task, IResultRowHandler handler) {
		String querySql = task.getViewSql();

		/**
		 * <p>
		 * 因存在源表的一个字段被映射为目的表的多个字段的情况
		 * </p>
		 * <p>
		 * 所以这里的map中, key存储的为映射的目的表字段名称，value存储的为映射的源表字段名称。
		 * </p>
		 */
		List<String> targetColumns = new ArrayList<String>();
		Map<String, Set<Integer>> orderMap = new HashMap<String, Set<Integer>>();
		int i = 0;
		for (Map.Entry<String, String> entry : task.getFieldsMapper().entrySet()) {
			targetColumns.add(entry.getKey());

			if (null == orderMap.get(entry.getValue())) {
				orderMap.put(entry.getValue(), new HashSet<Integer>());
			}
			orderMap.get(entry.getValue()).add(i);

			i++;
		}

		this.doDataTransfer(querySql, handler, targetColumns, orderMap, task.getValuesMapper());
	}

}